﻿App.Out = function() {

    return {

        currentFormValues: {},
        currentGridEditRow: null,

        getStore: function() {
            var store = new Ext.data.DirectStore({
                directFn: OutAction.pagedQuery,
                paramOrder: "start,limit,sort,dir,query",
                paramNames: {
                    dir: "dir",
                    sort: "sort",
                    start: "start",
                    limit: "limit",
                    query: ""
                },
                baseParams: {
                    dir: "",
                    sort: "",
                    start: 0,
                    limit: 50,
                    query: ""
                },
                paramsAsHash: true,
                totalProperty: 'totalCount',
                idProperty: 'id',
                root: 'result',
                remoteSort: true,
                fields: [{
                    name: 'id',
                    type: 'int'
                },
                {
                    name: 'operator'
                },
                {
                    name: 'createTime',
                    type: 'date',
                    dateFormat: 'time'
                },
                {
                    name: 'total',
                    type: 'float'
                },
                {
                    name: 'subList'
                }],
                listeners: {
                    scope: this,
                    load: function(store, recs) {
                        if (recs.length > 0) {
                            this.grid.getSelectionModel().selectFirstRow();
                            this.substore.loadData(recs[0].data.subList);
                        }
                    }
                }
            });
            return store;
        },

        getSubStore: function() {
            var store = new Ext.data.ArrayStore({
                idIndex: 0,
                fields: [{
                    name: 'id',
                    type: 'int'
                },
                {
                    name: 'productId'
                },
                {
                    name: 'name'
                },
                {
                    name: 'quantity',
                    type: "int"
                },
                {
                    name: 'price',
                    type: 'float'
                },
                {
                    name: 'subTotal',
                    type: 'float'
                }],
                remoteSort: false,
            });
            return store;
        },

        getForm: function() {
            this.productStore = new Ext.data.DirectStore({
                directFn: ProductAction.pagedQuery,
                paramOrder: "start,limit,sort,dir,query",
                paramNames: {
                    dir: "dir",
                    sort: "sort",
                    start: "start",
                    limit: "limit",
                    query: "query"
                },
                baseParams: {
                    dir: "",
                    sort: "",
                    start: 0,
                    limit: 10,
                    query: ""
                },
                paramsAsHash: true,
                totalProperty: 'totalCount',
                idProperty: 'id',
                root: 'result',
                remoteSort: true,
                fields: [{
                    name: 'id',
                    type: 'int'
                },
                {
                    name: 'name'
                },
                {
                    name: 'spec'
                },
                {
                    name: 'price',
                    type: 'float'
                }]
            });

            var resultTpl = new Ext.XTemplate('<tpl for="."><div class="search-item">',
                '<h3>[{id:this.highLight}]{name:this.highLight}</h3>',
                '规格：{sepec}<br/>',
                '单价：{price:this.number}<br/>',
                '</div></tpl>');

            resultTpl.highLight = function(value) {
                var key = App.Out.productStore.baseParams.query;
                var v = value ? value.toString() : '';
                if (Ext.isString(v) & Ext.isString(key)) {
                    if (key.length > 0) {
                        var re = new RegExp(key, "g");
                        return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
                    } else {
                        return v
                    }
                } else {
                    return v;
                }
            };

            resultTpl.number = function(v) {
                return Ext.util.Format.number(v, "0.00");
            };

            var productSearch = new Ext.form.ComboBox({
                store: this.productStore,
                displayField: 'id',
                typeAhead: false,
                loadingText: '正在加载...',
                width: 80,
                minChars: 1,
                pageSize: 10,
                listWidth: 300,
                lazyRender: true,
                listEmptyText: "没有产品",
                resizable: true,
                hideTrigger: true,
                tpl: resultTpl,
                itemSelector: 'div.search-item',
                onSelect: function(record) {
                    var row = App.Out.currentGridEditRow;
                    var rec = App.Out.frmStore.getAt(row);
                    if (rec) {
                        rec.data.name = record.data.name;
                        rec.data.price = record.data.price;
                    }
                    this.setValue(record.data.id);
                    this.collapse();
                }
            });

            this.frmStore = new Ext.data.ArrayStore({
                idIndex: 0,
                fields: [{
                    name: 'id'
                },
                {
                    name: 'productId'
                },
                {
                    name: 'name'
                },
                {
                    name: 'quantity',
                    type: "int"
                },
                {
                    name: 'price',
                    type: 'float'
                },
                {
                    name: 'subTotal',
                    type: 'float'
                }],
                listeners: {
                    scope: this,
                    remove: function(store, rec, index) {
                        this.frm.form.findField("price")
                            .setValue(Ext.util.Format.number(store.sum("subTotal"), '0.00'));
                    }
                }

            });

            var cm = new Ext.grid.ColumnModel([{
                header: "产品编号",
                width: 150,
                sortable: true,
                dataIndex: 'productId',
                editor: productSearch
            },
            {
                header: "产品名称",
                width: 150,
                sortable: true,
                dataIndex: 'name'
            },
            {
                header: "单价",
                width: 100,
                sortable: true,
                dataIndex: 'price',
                align: 'right',
                renderer: function(v) {
                    return Ext.util.Format.number(v, "0.00");
                }
            },
            {
                header: "产品数量",
                width: 100,
                sortable: true,
                dataIndex: 'quantity',
                align: 'center',
                editor: new Ext.form.TextField({
                    maskRe: /[A-Za-z0-9]/
                }),
                renderer: function(v) {
                    return Ext.util.Format.number(v, "0");
                }
            },
            {
                header: "小计",
                width: 120,
                sortable: true,
                dataIndex: 'subTotal',
                align: 'right',
                renderer: function(v) {
                    return Ext.util.Format.number(v, "0.00");
                }
            }]);

            this.frmGrid = new Ext.grid.EditorGridPanel({
                width: 660,
                height: 300,
                title: '进仓单明细',
                frame: true,
                clicksToEdit: 1,
                tbar: [{
                    text: '增加',
                    scope: this,
                    handler: function() {
                        var u = new this.frmGrid.store.recordType({
                            id: Ext.id(),
                            productId: '',
                            name: '',
                            quantity: 0,
                            price: 0,
                            subTotal: 0
                        });
                        this.frmGrid.store.insert(0, u);
                    }
                },
                {
                    text: '删除',
                    scope: this,
                    handler: function() {
                        var cell = this.frmGrid.getSelectionModel().getSelectedCell();
                        if (Ext.isArray(cell)) {
                            var rec = this.frmGrid.store.getAt(cell[0]);
                            if (!rec) {
                                return false;
                            }
                            this.frmGrid.store.remove(rec);
                        }
                    }
                }],
                store: this.frmStore,
                cm: cm,
                listeners: {
                    scope: this,
                    beforeedit: function(e) {
                        this.currentGridEditRow = e.row;
                    },
                    afteredit: function(e) {
                        e.record.data.subTotal = e.record.data.price * e.record.data.quantity;
                        e.grid.store.commitChanges();
                        App.Out.frm.form.findField("price")
                            .setValue(Ext.util.Format.number(e.grid.store.sum("subTotal"), '0.00'));
                    }
                }
            });

            var frm = new Ext.form.FormPanel({
                labelAlign: 'left',
                buttonAlign: 'center',
                bodyStyle: 'padding:5px',
                frame: true,
                labelWidth: 80,
                defaultType: 'textfield',
                defaults: {
                    allowBlank: true,
                    anchor: '90%',
                    enableKeyEvents: true
                },
                items: [{
                    xtype: 'hidden',
                    name: 'id',
                    value: ''
                },
                {
                    xtype: 'datefield',
                    name: 'createTime',
                    fieldLabel: '进仓日期',
                    maxlength: 20,
                    format: 'Y-m-d',
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                var obj = this.frm.form.findField("operator");
                                if (obj) obj.focus();
                            }
                        } //keypress
                    }
                },
                {
                    xtype: 'combo',
                    name: 'operator',
                    fieldLabel: '经办人',
                    maxlength: 50,
                    store: new Ext.data.DirectStore({
                        directFn: UserAction.list,
                        paramsAsHash: false,
                        totalProperty: 'totalCount',
                        idProperty: 'id',
                        root: '',
                        autoLoad: true,
                        remoteSort: false,
                        fields: [{
                            name: 'name'
                        }]
                    }),
                    mode: 'local',
                    forceSelection: true,
                    displayField: "name",
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                var obj = this.frm.form.findField("price");
                                if (obj) obj.focus();
                            }
                        } //keypress
                    }
                },
                {
                    name: 'price',
                    fieldLabel: '金额',
                    maxlength: 100,
                    allowBlank: true,
                    readOnly: true,
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                this.submit();
                            }
                        } //keypress
                    }
                },
                this.frmGrid],
                //items
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        this.frm.form.reset();
                        this.frm.form.setValues(this.currentFormValues);
                        this.frm.form.clearInvalid();
                    }
                }] //buttons
            }); //FormPanel
            return frm;
        },

        submit: function() {
            if (this.frm.form.isValid()) {
                vaR id = this.frm.form.findField("id").getValue();
                var params = {};
                for (var i = 0; i < this.frmStore.getCount(); i++) {
                    var rec = this.frmStore.getAt(i);
                    params["sub_id_" + i] = rec.data.productId;
                    params["sub_q_" + i] = rec.data.quantity;
                }
                this.frm.form.api = {
                    submit: OutAction.save
                };
                this.frm.form.doAction("directsubmit", {
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: params,
                    success: function(form, action) {
                        var msg = "";
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.frm.form.reset();
                                this.frmStore.removeAll();
                                msg = "新进仓单已保存。";
                            } else {
                                this.dlg.hide();
                                msg = "进仓单已更新。";
                            }
                        }
                        Ext.Msg.alert('信息', msg);
                    },
                    failure: function(form, action) {
                        if (action.result) {
                            if (action.result.msg) Ext.Msg.alert('错误', action.result.msg);
                        }
                        if (action.message) Ext.Msg.alert('错误', action.message);
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 700,
                height: 500,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.frm],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.frm.form.waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        this.frm.form.setValues(this.currentFormValues);
                        this.frm.form.clearInvalid();
                    }
                }
            }); //dlg
            return dlg;
        },

        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();

            this.grid = new Ext.grid.GridPanel({
                region: 'center',
                tbar: new Ext.PagingToolbar({
                    pageSize: 50,
                    displayInfo: true,
                    store: this.store,
                    items: ['-', {
                        text: '增加',
                        scope: this,
                        handler: this.add
                    },
                    {
                        text: '编辑',
                        scope: this,
                        handler: this.edit
                    },
                    {
                        text: '删除',
                        scope: this,
                        handler: this.del
                    }]
                }),
                store: this.store,
                sm: sm,
                columns: [sm, {
                    header: "进仓单号",
                    width: 100,
                    sortable: true,
                    dataIndex: 'id'
                },
                {
                    header: "经手人",
                    width: 150,
                    sortable: true,
                    dataIndex: 'operator'
                },
                {
                    header: "进仓时间",
                    width: 300,
                    sortable: true,
                    dataIndex: 'createTime',
                    renderer: Ext.util.Format.dateRenderer('Y-m-d')
                },
                {
                    header: "金额",
                    width: 200,
                    sortable: true,
                    dataIndex: 'total',
                    align: 'right',
                    renderer: function(v) {
                        return Ext.util.Format.number(v, "0.00");
                    }
                }],
                listeners: {
                    scope: this,
                    rowclick: function(grid, rowIndex, e) {
                        var rec = this.store.getAt(rowIndex);
                        if (rec) {
                            this.substore.loadData(rec.data.subList);
                        }
                    }
                }
            });

            this.subGrid = new Ext.grid.GridPanel({
                store: this.substore,
                title: '进仓单明细',
                region: 'south',
                layout: 'fit',
                split: true,
                height: 225,
                minSize: 175,
                maxSize: 400,
                columns: [{
                    header: "产品编号",
                    width: 100,
                    sortable: true,
                    dataIndex: 'productId'
                },
                {
                    header: "产品名称",
                    width: 150,
                    sortable: true,
                    dataIndex: 'name'
                },
                {
                    header: "单价",
                    width: 200,
                    sortable: true,
                    dataIndex: 'price',
                    align: 'right',
                    renderer: function(v) {
                        return Ext.util.Format.number(v, "0.00");
                    }
                },
                {
                    header: "产品数量",
                    width: 300,
                    sortable: true,
                    dataIndex: 'quantity',
                    align: 'center'
                },
                {
                    header: "小计",
                    width: 200,
                    sortable: true,
                    dataIndex: 'subTotal',
                    align: 'right',
                    renderer: function(v) {
                        return Ext.util.Format.number(v, "0.00");
                    }
                }]
            });

            panel.add(new Ext.Panel({
                layout: "border",
                items: [this.grid, this.subGrid]
            }));

            this.store.load({
                dir: "",
                sort: "",
                start: 0,
                limit: 50
            });
        },

        add: function() {
            var d = new Date();
            Ext.apply(this.currentFormValues, {
                id: '',
                createTime: Ext.util.Format.date(d, 'Y-m-d'),
                operator: "",
                price: '0.00'
            });
            this.frmStore.removeAll();
            this.dlg.setTitle("增加进仓单");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑进仓单");
                var rec = this.grid.getSelectionModel().getSelected();
                Ext.apply(this.currentFormValues, {
                    id: rec.data.id,
                    createTime: rec.data.createTime,
                    operator: rec.data.operator,
                    price: Ext.util.Format.number(rec.data.total, "0.00")
                });
                this.frmStore.loadData(rec.data.subList);
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的进仓单。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                var titles = '';
                for (var i = 0; i < recs.length; i++) {
                    var data = recs[i].data;
                    ids.push(data.id);
                    titles += data.id + '<br>';
                }
                Ext.Msg.confirm('删除进仓单', '确定删除以下进仓单？<br><font color="red">' + titles + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        OutAction.remove(ids.toString(),
                        function(data, e) {
                            if (data) {
                                if (data.success) {
                                    Ext.Msg.alert('信息', '已成功删除进仓单。');
                                    App.Out.store.reload();
                                } else {
                                    Ext.Msg.alert('信息', data.msg);
                                }
                            } else {
                                Ext.Msg.alert('信息', e.msg);
                            }
                        })
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的进仓单！');
            }
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            }; //if(!this.store)
            if (!this.substore) {
                this.substore = this.getSubStore();
            }; //if(!this.subStore)
            if (!this.frm) {
                this.frm = this.getForm();
            }; //if(!this.frm)

            if (!this.dlg) {
                this.dlg = this.getDialog();
            }; //if(!this.dlg)
            this.createGrid(id);

        }

    }; //return
} (); //function
